<!DOCTYPE html><html lang="zh-CN" data-theme="light"><head><meta charset="UTF-8"><meta http-equiv="X-UA-Compatible" content="IE=edge"><meta name="viewport" content="width=device-width, initial-scale=1.0,viewport-fit=cover"><title>Apache Omid Timestamp Oracle 组件实现原理 | flyingzc's blog</title><meta name="author" content="flyingzc"><meta name="copyright" content="flyingzc"><meta name="format-detection" content="telephone=no"><meta name="theme-color" content="#ffffff"><meta name="description" content="Omid Timestamp Oracle 组件实现原理作用生成全局单调递增的时间戳，支持获取操作和崩溃恢复。 功能1234567891011121314151617181920212223241.生成全局单调递增的时间戳(支持崩溃恢复)    api        next            返回下一个时间戳        getLast            返回最后一个分配的时间戳(当前">
<meta property="og:type" content="article">
<meta property="og:title" content="Apache Omid Timestamp Oracle 组件实现原理">
<meta property="og:url" content="https://flyingzc.github.io/articles/omid/omid02-timestamp-oracle.html">
<meta property="og:site_name" content="flyingzc&#39;s blog">
<meta property="og:description" content="Omid Timestamp Oracle 组件实现原理作用生成全局单调递增的时间戳，支持获取操作和崩溃恢复。 功能1234567891011121314151617181920212223241.生成全局单调递增的时间戳(支持崩溃恢复)    api        next            返回下一个时间戳        getLast            返回最后一个分配的时间戳(当前">
<meta property="og:locale" content="zh_CN">
<meta property="og:image" content="https://flyingzc.github.io/images/zc-icon.jpeg">
<meta property="article:published_time" content="2024-06-27T16:00:00.000Z">
<meta property="article:modified_time" content="2025-01-21T01:51:41.213Z">
<meta property="article:author" content="flyingzc">
<meta property="article:tag" content="Transaction">
<meta property="article:tag" content="Omid">
<meta name="twitter:card" content="summary">
<meta name="twitter:image" content="https://flyingzc.github.io/images/zc-icon.jpeg"><script type="application/ld+json">{
  "@context": "https://schema.org",
  "@type": "BlogPosting",
  "headline": "Apache Omid Timestamp Oracle 组件实现原理",
  "url": "https://flyingzc.github.io/articles/omid/omid02-timestamp-oracle.html",
  "image": "https://flyingzc.github.io/images/zc-icon.jpeg",
  "datePublished": "2024-06-27T16:00:00.000Z",
  "dateModified": "2025-01-21T01:51:41.213Z",
  "author": [
    {
      "@type": "Person",
      "name": "flyingzc",
      "url": "https://flyingzc.github.io/"
    }
  ]
}</script><link rel="shortcut icon" href="/images/zc-icon.jpeg"><link rel="canonical" href="https://flyingzc.github.io/articles/omid/omid02-timestamp-oracle.html"><link rel="preconnect" href="//cdn.jsdelivr.net"/><link rel="preconnect" href="//busuanzi.ibruce.info"/><meta name="google-site-verification" content="DentpX3LnP_WNgEeFnNIcTZZky-Bby-zL-uI_9GqTAw"/><link rel="stylesheet" href="/css/index.css"><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/@fortawesome/fontawesome-free/css/all.min.css"><script>
    (() => {
      
    const saveToLocal = {
      set: (key, value, ttl) => {
        if (!ttl) return
        const expiry = Date.now() + ttl * 86400000
        localStorage.setItem(key, JSON.stringify({ value, expiry }))
      },
      get: key => {
        const itemStr = localStorage.getItem(key)
        if (!itemStr) return undefined
        const { value, expiry } = JSON.parse(itemStr)
        if (Date.now() > expiry) {
          localStorage.removeItem(key)
          return undefined
        }
        return value
      }
    }

    window.btf = {
      saveToLocal,
      getScript: (url, attr = {}) => new Promise((resolve, reject) => {
        const script = document.createElement('script')
        script.src = url
        script.async = true
        Object.entries(attr).forEach(([key, val]) => script.setAttribute(key, val))
        script.onload = script.onreadystatechange = () => {
          if (!script.readyState || /loaded|complete/.test(script.readyState)) resolve()
        }
        script.onerror = reject
        document.head.appendChild(script)
      }),
      getCSS: (url, id) => new Promise((resolve, reject) => {
        const link = document.createElement('link')
        link.rel = 'stylesheet'
        link.href = url
        if (id) link.id = id
        link.onload = link.onreadystatechange = () => {
          if (!link.readyState || /loaded|complete/.test(link.readyState)) resolve()
        }
        link.onerror = reject
        document.head.appendChild(link)
      }),
      addGlobalFn: (key, fn, name = false, parent = window) => {
        if (!false && key.startsWith('pjax')) return
        const globalFn = parent.globalFn || {}
        globalFn[key] = globalFn[key] || {}
        globalFn[key][name || Object.keys(globalFn[key]).length] = fn
        parent.globalFn = globalFn
      }
    }
  
      
      const activateDarkMode = () => {
        document.documentElement.setAttribute('data-theme', 'dark')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#0d0d0d')
        }
      }
      const activateLightMode = () => {
        document.documentElement.setAttribute('data-theme', 'light')
        if (document.querySelector('meta[name="theme-color"]') !== null) {
          document.querySelector('meta[name="theme-color"]').setAttribute('content', '#ffffff')
        }
      }

      btf.activateDarkMode = activateDarkMode
      btf.activateLightMode = activateLightMode

      const theme = saveToLocal.get('theme')
    
          theme === 'dark' ? activateDarkMode() : theme === 'light' ? activateLightMode() : null
        
      
      const asideStatus = saveToLocal.get('aside-status')
      if (asideStatus !== undefined) {
        document.documentElement.classList.toggle('hide-aside', asideStatus === 'hide')
      }
    
      
    const detectApple = () => {
      if (/iPad|iPhone|iPod|Macintosh/.test(navigator.userAgent)) {
        document.documentElement.classList.add('apple')
      }
    }
    detectApple()
  
    })()
  </script><script async="async" src="https://pagead2.googlesyndication.com/pagead/js/adsbygoogle.js"></script><script>(adsbygoogle = window.adsbygoogle || []).push({
  google_ad_client: '',
  enable_page_level_ads: 'true'
});</script><script>const GLOBAL_CONFIG = {
  root: '/',
  algolia: undefined,
  localSearch: undefined,
  translate: undefined,
  highlight: {"plugin":"highlight.js","highlightCopy":true,"highlightLang":true,"highlightHeightLimit":false,"highlightFullpage":false,"highlightMacStyle":false},
  copy: {
    success: '复制成功',
    error: '复制失败',
    noSupport: '浏览器不支持'
  },
  relativeDate: {
    homepage: false,
    post: false
  },
  runtime: '',
  dateSuffix: {
    just: '刚刚',
    min: '分钟前',
    hour: '小时前',
    day: '天前',
    month: '个月前'
  },
  copyright: undefined,
  lightbox: 'null',
  Snackbar: undefined,
  infinitegrid: {
    js: 'https://cdn.jsdelivr.net/npm/@egjs/infinitegrid/dist/infinitegrid.min.js',
    buttonText: '加载更多'
  },
  isPhotoFigcaption: false,
  islazyloadPlugin: false,
  isAnchor: false,
  percent: {
    toc: true,
    rightside: false,
  },
  autoDarkmode: false
}</script><script id="config-diff">var GLOBAL_CONFIG_SITE = {
  title: 'Apache Omid Timestamp Oracle 组件实现原理',
  isHighlightShrink: false,
  isToc: true,
  pageType: 'post'
}</script><link rel="stylesheet" href="/self/github-dark.css"><meta name="generator" content="Hexo 7.0.0"></head><body><div id="sidebar"><div id="menu-mask"></div><div id="sidebar-menus"><div class="avatar-img text-center"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="site-data text-center"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div></div></div><div class="post" id="body-wrap"><header class="post-bg" id="page-header"><nav id="nav"><span id="blog-info"><a class="nav-site-title" href="/"><span class="site-name">flyingzc's blog</span></a><a class="nav-page-title" href="/"><span class="site-name">Apache Omid Timestamp Oracle 组件实现原理</span></a></span><div id="menus"><div class="menus_items"><div class="menus_item"><a class="site-page" href="/"><i class="fa-fw fas fa-home"></i><span> 主页</span></a></div><div class="menus_item"><a class="site-page" href="/archives/"><i class="fa-fw fas fa-archive"></i><span> 归档</span></a></div><div class="menus_item"><a class="site-page" href="/tags/"><i class="fa-fw fas fa-tags"></i><span> 标签</span></a></div><div class="menus_item"><a class="site-page" href="/categories/"><i class="fa-fw fas fa-folder-open"></i><span> 分类</span></a></div><div class="menus_item"><a class="site-page" href="/about/"><i class="fa-fw fas fa-heart"></i><span> 关于我</span></a></div></div><div id="toggle-menu"><span class="site-page"><i class="fas fa-bars fa-fw"></i></span></div></div></nav><div id="post-info"><h1 class="post-title">Apache Omid Timestamp Oracle 组件实现原理</h1><div id="post-meta"><div class="meta-firstline"><span class="post-meta-date"><i class="far fa-calendar-alt fa-fw post-meta-icon"></i><span class="post-meta-label">发表于</span><time class="post-meta-date-created" datetime="2024-06-27T16:00:00.000Z" title="发表于 2024-06-28 00:00:00">2024-06-28</time><span class="post-meta-separator">|</span><i class="fas fa-history fa-fw post-meta-icon"></i><span class="post-meta-label">更新于</span><time class="post-meta-date-updated" datetime="2025-01-21T01:51:41.213Z" title="更新于 2025-01-21 09:51:41">2025-01-21</time></span><span class="post-meta-categories"><span class="post-meta-separator">|</span><i class="fas fa-inbox fa-fw post-meta-icon"></i><a class="post-meta-categories" href="/categories/Omid/">Omid</a></span></div><div class="meta-secondline"><span class="post-meta-separator">|</span><span class="post-meta-pv-cv" id="" data-flag-title=""><i class="far fa-eye fa-fw post-meta-icon"></i><span class="post-meta-label">浏览量:</span><span id="busuanzi_value_page_pv"><i class="fa-solid fa-spinner fa-spin"></i></span></span></div></div></div></header><main class="layout" id="content-inner"><div id="post"><article class="container post-content" id="article-container"><h1 id="Omid-Timestamp-Oracle-组件实现原理"><a href="#Omid-Timestamp-Oracle-组件实现原理" class="headerlink" title="Omid Timestamp Oracle 组件实现原理"></a>Omid Timestamp Oracle 组件实现原理</h1><h2 id="作用"><a href="#作用" class="headerlink" title="作用"></a>作用</h2><p>生成全局单调递增的时间戳，支持获取操作和崩溃恢复。</p>
<h2 id="功能"><a href="#功能" class="headerlink" title="功能"></a>功能</h2><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br></pre></td><td class="code"><pre><code class="hljs km">1.生成全局单调递增的时间戳(支持崩溃恢复)<br>    api<br>        next<br>            返回下一个时间戳<br>        getLast<br>            返回最后一个分配的时间戳(当前时间戳)<br>    实现方式<br>        TimestampOracleImpl<br>            单调递增的时间戳<br>                在分配时间戳时，如果当前的最大时间戳已经用完，它会触发一个后台任务来更新最大时间戳<br>            next：<br>                分配下一个时间戳。如果当前的最大时间戳已经用完，它会等待后台任务分配新的时间戳<br>        WorldClockOracleImpl<br>            基于世界时间(System.timestamp)生成全局单调递增的时间戳<br>2.存储时间戳<br>    存储方式<br>        in memory<br>        zk<br>        hbase<br>    api<br>        updateMaxTimestamp<br>            更新最大时间戳<br>        getMaxTimestamp<br>            获取最大时间戳<br></code></pre></td></tr></table></figure>

<h2 id="类"><a href="#类" class="headerlink" title="类"></a>类</h2><h3 id="TimestampStorage"><a href="#TimestampStorage" class="headerlink" title="TimestampStorage"></a>TimestampStorage</h3><p>存储时间戳</p>
<p>方法:<br>updateMaxTimestamp 更新最大时间戳<br>getMaxTimestamp 获取最大时间戳</p>
<p>实现类:</p>
<figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br></pre></td><td class="code"><pre><code class="hljs km">TimestampStorage<br>    InMemoryTimestampStorage in TimestampOracleImpl (org.apache.omid.tso) 使用内存存储<br>    ZKTimestampStorage (org.apache.omid.timestamp.storage) 使用 zk 存储<br>    HBaseTimestampStorage (org.apache.omid.timestamp.storage) 使用 hbase 存储<br>    InMemoryTimestampStorage in WorldClockOracleImpl (org.apache.omid.tso) 使用内存存储<br></code></pre></td></tr></table></figure>

<h4 id="ZKTimestampStorage"><a href="#ZKTimestampStorage" class="headerlink" title="ZKTimestampStorage"></a>ZKTimestampStorage</h4><p>通过 zk curator DistributedAtomicLong 实现 <code>DistributedAtomicLong timestamp</code></p>
<p>方法：<br>updateMaxTimestamp():<br>    执行 timestamp.compareAndSet(previousMaxTimestamp, newMaxTimestamp)<br>getMaxTimestamp():<br>    返回 timestamp.get()</p>
<h3 id="TimestampOracle"><a href="#TimestampOracle" class="headerlink" title="TimestampOracle"></a>TimestampOracle</h3><p>TimestampOracle 提供了一个服务，用于<code>生成单调递增的时间戳</code>。</p>
<p>方法:<br>initialize()<br>用于初始化时间戳服务。</p>
<p>next()<br>返回下一个时间戳。</p>
<p>getLast()<br>返回最后一个分配的时间戳(当前时间戳)</p>
<h4 id="实现类"><a href="#实现类" class="headerlink" title="实现类"></a>实现类</h4><figure class="highlight plaintext"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br></pre></td><td class="code"><pre><code class="hljs km">TimestampOracle (org.apache.omid.tso)<br>    TimestampOracleImpl (org.apache.omid.tso)<br>        PausableTimestampOracle (org.apache.omid.tso)<br>    WorldClockOracleImpl (org.apache.omid.tso)<br></code></pre></td></tr></table></figure>

<h4 id="TimestampOracleImpl"><a href="#TimestampOracleImpl" class="headerlink" title="TimestampOracleImpl"></a>TimestampOracleImpl</h4><h5 id="initialize"><a href="#initialize" class="headerlink" title="initialize()"></a>initialize()</h5><p>1.从存储中获取 maxTimestamp;<br>2.初始化 AllocateTimestampBatchTask 用于分配时间戳,并执行一次.</p>
<h5 id="next"><a href="#next" class="headerlink" title="next()"></a>next()</h5><p>生成下一个时间戳。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br><span class="line">22</span><br><span class="line">23</span><br><span class="line">24</span><br><span class="line">25</span><br><span class="line">26</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-meta">@Override</span><br><span class="hljs-keyword">public</span> <span class="hljs-type">long</span> <span class="hljs-title function_">next</span><span class="hljs-params">()</span> &#123;<br>    lastTimestamp += CommitTable.MAX_CHECKPOINTS_PER_TXN;<br>    <span class="hljs-comment">// 当前时间戳超过分配阈值时，触发执行时间戳批次分配任务</span><br>    <span class="hljs-keyword">if</span> (lastTimestamp &gt;= nextAllocationThreshold) &#123;<br>        <span class="hljs-comment">// 设置下一次分配阈值为Long.MAX_VALUE，确保只有一个线程会执行分配任务</span><br>        nextAllocationThreshold = Long.MAX_VALUE; <br>        executor.execute(allocateTimestampsBatchTask);<br>    &#125;<br>    <span class="hljs-comment">// 当lastTimestamp超过当前已分配的最大时间戳时，等待新一批时间戳被分配</span><br>    <span class="hljs-keyword">if</span> (lastTimestamp &gt;= maxTimestamp) &#123;<br>        <span class="hljs-keyword">assert</span> (maxTimestamp &lt;= maxAllocatedTimestamp);<br>        <span class="hljs-comment">// 自旋等待，直到已分配的最大时间戳被更新</span><br>        <span class="hljs-keyword">while</span> (maxAllocatedTimestamp == maxTimestamp) &#123;<br>            <span class="hljs-comment">// 自旋</span><br>        &#125;<br>        <span class="hljs-keyword">assert</span> (maxAllocatedTimestamp &gt; maxTimestamp);<br>        <span class="hljs-comment">// 更新当前最大时间戳并计算下次分配的阈值</span><br>        maxTimestamp = maxAllocatedTimestamp;<br>        nextAllocationThreshold = maxTimestamp - TIMESTAMP_REMAINING_THRESHOLD;<br>        <span class="hljs-keyword">assert</span> (nextAllocationThreshold &gt; lastTimestamp &amp;&amp; nextAllocationThreshold &lt; maxTimestamp);<br>        <span class="hljs-keyword">assert</span> (lastTimestamp &lt; maxTimestamp);<br>    &#125;<br>    <span class="hljs-comment">// 返回新生成的时间戳</span><br>    <span class="hljs-keyword">return</span> lastTimestamp;<br>&#125;<br></code></pre></td></tr></table></figure>

<h5 id="AllocateTimestampBatchTask"><a href="#AllocateTimestampBatchTask" class="headerlink" title="AllocateTimestampBatchTask"></a>AllocateTimestampBatchTask</h5><p>定时任务批量更新存储系统中最大的时间戳，每次预分配 TIMESTAMP_BATCH 数量的时间戳。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">static</span> <span class="hljs-keyword">final</span> <span class="hljs-type">long</span> <span class="hljs-variable">TIMESTAMP_BATCH</span> <span class="hljs-operator">=</span> <span class="hljs-number">10_000_000</span> * CommitTable.MAX_CHECKPOINTS_PER_TXN; <span class="hljs-comment">// 10 million</span><br><span class="hljs-type">long</span> <span class="hljs-variable">newMaxTimestamp</span> <span class="hljs-operator">=</span> previousMaxTimestamp + TIMESTAMP_BATCH;<br></code></pre></td></tr></table></figure>

<h4 id="WorldClockOracleImpl"><a href="#WorldClockOracleImpl" class="headerlink" title="WorldClockOracleImpl"></a>WorldClockOracleImpl</h4><p>基于世界时间的单调递增时间戳。</p>
<p>initialize<br>从 TimestampStorage 中获取最大的时间戳，并启动定时任务来定期更新最大时间戳。</p>
<p>next<br>用于获取下一个时间戳。<br>如果当前时间戳可用，则直接返回；<br>否则，等待定时任务分配新的时间戳。</p>
<p>getLast<br>方法返回最后一个时间戳。</p>
<h5 id="AllocateTimestampBatchTask-run"><a href="#AllocateTimestampBatchTask-run" class="headerlink" title="AllocateTimestampBatchTask#run"></a>AllocateTimestampBatchTask#run</h5><p>定时任务预分配时间戳。</p>
<figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-comment">// 预测一个未来的时间窗口内允许的最大事务时间戳.</span><br><span class="hljs-comment">// 当前时间（System.currentTimeMillis()）加上一个预设的时间间隔TIMESTAMP_INTERVAL_MS，然后乘以每毫秒允许的最大事务数MAX_TX_PER_MS</span><br><span class="hljs-type">long</span> <span class="hljs-variable">newMaxTime</span> <span class="hljs-operator">=</span> (System.currentTimeMillis() + TIMESTAMP_INTERVAL_MS) * MAX_TX_PER_MS;<br></code></pre></td></tr></table></figure>

<h5 id="next-1"><a href="#next-1" class="headerlink" title="next()"></a>next()</h5><figure class="highlight java"><table><tr><td class="gutter"><pre><span class="line">1</span><br><span class="line">2</span><br><span class="line">3</span><br><span class="line">4</span><br><span class="line">5</span><br><span class="line">6</span><br><span class="line">7</span><br><span class="line">8</span><br><span class="line">9</span><br><span class="line">10</span><br><span class="line">11</span><br><span class="line">12</span><br><span class="line">13</span><br><span class="line">14</span><br><span class="line">15</span><br><span class="line">16</span><br><span class="line">17</span><br><span class="line">18</span><br><span class="line">19</span><br><span class="line">20</span><br><span class="line">21</span><br></pre></td><td class="code"><pre><code class="hljs java"><span class="hljs-keyword">public</span> <span class="hljs-type">long</span> <span class="hljs-title function_">next</span><span class="hljs-params">()</span> &#123;<br>    <span class="hljs-type">long</span> <span class="hljs-variable">currentMsFirstTimestamp</span> <span class="hljs-operator">=</span> System.currentTimeMillis() * MAX_TX_PER_MS; <span class="hljs-comment">// 通过当前时间乘以每毫秒的最大事务数来计算当前毫秒的第一个时间戳</span><br>    lastTimestamp += CommitTable.MAX_CHECKPOINTS_PER_TXN;<br>    <span class="hljs-keyword">if</span> (lastTimestamp &gt;= currentMsFirstTimestamp) &#123; <span class="hljs-comment">// 如果lastTimestamp大于等于当前毫秒的第一个时间戳，直接返回lastTimestamp</span><br>        <span class="hljs-keyword">return</span> lastTimestamp;<br>    &#125;<br>    <span class="hljs-comment">// 当前 timestamp 的第一个时间戳 &gt;= 最大时间戳.这里sleep等待 allocate 线程进行分配</span><br>    <span class="hljs-keyword">if</span> (currentMsFirstTimestamp &gt;= maxTimestamp) &#123; <span class="hljs-comment">// Intentional race to reduce synchronization overhead in every access to maxTimestamp                                                                                                                       </span><br>        <span class="hljs-keyword">while</span> (maxAllocatedTime &lt;= currentMsFirstTimestamp) &#123; <span class="hljs-comment">// Waiting for the interval allocation</span><br>            <span class="hljs-keyword">try</span> &#123;<br>                Thread.sleep(<span class="hljs-number">1000</span>);<br>            &#125; <span class="hljs-keyword">catch</span> (InterruptedException e) &#123;<br>                <span class="hljs-keyword">continue</span>;<br>            &#125;<br>        &#125;<br>        <span class="hljs-keyword">assert</span> (maxAllocatedTime &gt; maxTimestamp);<br>        maxTimestamp = maxAllocatedTime;<br>    &#125;<br>    lastTimestamp = currentMsFirstTimestamp;<br>    <span class="hljs-keyword">return</span> lastTimestamp;<br>&#125;<br></code></pre></td></tr></table></figure>
<link rel="stylesheet" href="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10/dist/style.css"><script src="https://fastly.jsdelivr.net/npm/d3@7"></script><script src="https://fastly.jsdelivr.net/npm/markmap-view@0.18.10"></script><script src="https://fastly.jsdelivr.net/npm/markmap-toolbar@0.18.10"></script>
<link rel="stylesheet" href="/css/markmap.css">

<script src="/js/markmap.js"></script>
</article><div class="post-copyright"><div class="post-copyright__author"><span class="post-copyright-meta"><i class="fas fa-circle-user fa-fw"></i>文章作者: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io">flyingzc</a></span></div><div class="post-copyright__type"><span class="post-copyright-meta"><i class="fas fa-square-arrow-up-right fa-fw"></i>文章链接: </span><span class="post-copyright-info"><a href="https://flyingzc.github.io/articles/omid/omid02-timestamp-oracle.html">https://flyingzc.github.io/articles/omid/omid02-timestamp-oracle.html</a></span></div><div class="post-copyright__notice"><span class="post-copyright-meta"><i class="fas fa-circle-exclamation fa-fw"></i>版权声明: </span><span class="post-copyright-info">本博客所有文章除特别声明外，均采用 <a href="https://creativecommons.org/licenses/by-nc-sa/4.0/" target="_blank">CC BY-NC-SA 4.0</a> 许可协议。转载请注明来源 <a href="https://flyingzc.github.io" target="_blank">flyingzc's blog</a>！</span></div></div><div class="tag_share"><div class="post-meta__tag-list"><a class="post-meta__tags" href="/tags/Transaction/">Transaction</a><a class="post-meta__tags" href="/tags/Omid/">Omid</a></div><div class="post-share"><div class="social-share" data-image="/images/zc-icon.jpeg" data-sites="facebook,twitter,wechat,weibo,qq"></div><link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/css/share.min.css" media="print" onload="this.media='all'"><script src="https://cdn.jsdelivr.net/npm/butterfly-extsrc/sharejs/dist/js/social-share.min.js" defer></script></div></div><nav class="pagination-post" id="pagination"></nav><div class="relatedPosts"><div class="headline"><i class="fas fa-thumbs-up fa-fw"></i><span>相关推荐</span></div><div class="relatedPosts-list"><a class="pagination-related" href="/articles/omid/omid01-build.html" title="Apache Omid Idea 环境搭建"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-05-30</div><div class="info-item-2">Apache Omid Idea 环境搭建</div></div><div class="info-2"><div class="info-item-1">IDEA 搭建 Apache Omid 源码 DEBUG 环境Apache Omid 在 Apache HBase 之上提供了多行分布式事务的能力，支持全局 MVCC 功能。简单介绍编译过程。 1.下载 HBase2 并启动https://dlcdn.apache.org/hbase/ 配置环境变量 12export HBASE_HOME=/xxx/hbase-2.4.18export PATH=$PATH:$HBASE_HOME/bin:  2.编译代码编译1git clone https://github.com/apache/phoenix-omid  基于最新的 master af8e377affcd76b1cbde5cab3513731b23bd51fc 编译。 maven 依赖处理有几处编译报错，处理如下： 根 pom 里添加: 12345&lt;dependency&gt;    &lt;groupId&gt;org.glassfish&lt;/groupId&gt;    &lt;artifactId&gt;javax.el&lt;/artifactId&gt;...</div></div></div></a><a class="pagination-related" href="/articles/omid/omid03-tso.html" title="Apache Omid TSO 组件实现原理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-07-02</div><div class="info-item-2">Apache Omid TSO 组件实现原理</div></div><div class="info-2"><div class="info-item-1">Apache Omid TSO 组件实现原理作用独立进程，处理全局事务之间的并发冲突。 流程TSOChannelHandler#channelRead -&gt; AbstractRequestProcessor -&gt; PersistenceProcessorHandler 总体流程123456789thread1    TSOChannelHandler#channelRead        AbstractRequestProcessor#timestampRequest 接收 client 请求，创建 RequestEvent 并 publishthread2    AbstractRequestProcessor#onEvent 处理 RequestEvent 请求        AbstractRequestProcessor#handleRequest            PersistenceProcessorImpl#addTimestampToBatch 创建 PersistEvent,当 batch 满了发送事件thread3   ...</div></div></div></a><a class="pagination-related" href="/articles/omid/omid04-client.html" title="Apache Omid Client 组件实现原理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2024-07-23</div><div class="info-item-2">Apache Omid Client 组件实现原理</div></div><div class="info-2"><div class="info-item-1">Apache Omid Client 组件实现原理作用通过 TransactionManager 开启&#x2F;提交&#x2F;回滚事务，提供事务内快照隔离级别的读写操作。 使用123456789101112131415// 1.创建 transaction managerTransactionManager tm = HBaseTransactionManager.newInstance();// 2.通过 transactin manger 开启事务Transaction tx0 = tm.begin();// 3.事务内插入数据byte[] rowId = rowIdGenerator.getRowId();Put initialPut = new Put(rowId);initialPut.addColumn(family, qualifier, initialData);txTable.put(tx0, initialPut);// 4.事务内读取数据Get tx2Get = new Get(rowId);tx2Get.addColumn(family,...</div></div></div></a><a class="pagination-related" href="/articles/distributed/distributed01-consistency.html" title="分布式一致性模型"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2023-12-19</div><div class="info-item-2">分布式一致性模型</div></div><div class="info-2"><div class="info-item-1">分布式一致性模型分布式一致性探讨的问题：由于分布式环境 CAP 理论的存在，当用户对数据发生读写操作时可能产生的结果。 线性一致性所有操作被记录在一条时间线上,任意两个事件都可以比较先后顺序.任何客户端一定读取到最新写入的数据(包括从其他客户端写入的)。 实现:依赖全局时钟实现，保证所有操作记录在一条时间线上。 顺序一致性多个写操作全局有序，单个客户端看到的写操作的顺序相同。但是不保证各个客户端一定读取到最新值，只能保证一个客户端读取到写入的新值后，不会再读取到旧值即可。 实现: Zookeeper 因果一致性所有过程必须以相同的顺序看到因果相关的操作。没有因果关系的并发写入可以被不同的进程以不同的顺序观察到。也就是说有因果关系的操作按照因果顺序读取到结果，没有关系的操作之间可能会乱序。 实现：依赖逻辑时钟实现。 参考jepsen     </div></div></div></a><a class="pagination-related" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-09-11</div><div class="info-item-2">Apache Ignite IDEA 环境搭建</div></div><div class="info-2"><div class="info-item-1">Apache Ignite IDEA 源码 DEBUG 环境搭建Apache Ignite是一个高性能、集成化和分布式的内存计算平台，本文将介绍如何在 IDEA 中搭建 Ignite 源码调试环境。 Idea 代码编译Ignite 项目构建比较简单。使用 JDK 11，执行如下命令编译即可。 1mvn clean install -DskipITs -DskipTests --settings ~/.m2/settings.xml  参数说明：  -DskipITs：跳过集成测试 -DskipTests：跳过单元测试 --settings ~/.m2/settings.xml：指定 Maven 配置文件路径  启动类Ignite提供了多种启动方式，可以通过以下主要启动类进行调试：  org.apache.ignite.startup.cmdline.CommandLineStartup：命令行启动  运行事务测试要运行 Ignite 的事务测试示例，需要进行以下配置： 修改 ignite-examples&#x2F;config&#x2F;example-default.xml...</div></div></div></a><a class="pagination-related" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理"><div class="cover" style="background: var(--default-bg-color)"></div><div class="info text-center"><div class="info-1"><div class="info-item-1"><i class="far fa-calendar-alt fa-fw"></i> 2025-09-18</div><div class="info-item-2">Apache Ignite 分布式事务原理</div></div><div class="info-2"><div class="info-item-1">Apache Ignite 分布式事务原理Apache Ignite 是一个高性能、集成化和分布式的内存计算平台，支持在大数据量场景下进行 SQL 查询、计算和事务处理。在本文中，我们将深入探讨 Apache Ignite 中分布式事务的实现原理。 使用示例首先，让我们通过一个简单的示例来了解如何在 Ignite 中使用事务： 12345678910111213141516171819202122// 启动 ignitetry (Ignite ignite = Ignition.start(&quot;examples/config/example-ignite.xml&quot;)) &#123;    // 配置    CacheConfiguration&lt;Integer, Account&gt; cfg = new CacheConfiguration&lt;&gt;(CACHE_NAME);    cfg.setAtomicityMode(CacheAtomicityMode.TRANSACTIONAL);    // 创建缓存    try...</div></div></div></a></div></div></div><div class="aside-content" id="aside-content"><div class="card-widget card-info text-center"><div class="avatar-img"><img src="/images/zc-icon.jpeg" onerror="this.onerror=null;this.src='/img/friend_404.gif'" alt="avatar"/></div><div class="author-info-name">flyingzc</div><div class="author-info-description">不积跬步无以至千里<br/>不积小流无以成江海</div><div class="site-data"><a href="/archives/"><div class="headline">文章</div><div class="length-num">84</div></a><a href="/tags/"><div class="headline">标签</div><div class="length-num">36</div></a><a href="/categories/"><div class="headline">分类</div><div class="length-num">29</div></a></div><a id="card-info-btn" target="_blank" rel="noopener" href="https://github.com/FlyingZC"><i class="fab fa-github"></i><span>Follow Me</span></a><div class="card-info-social-icons"><a class="social-icon" href="https://github.com/FlyingZC" target="_blank" title="Github"><i class="fab fa-github" style="color: #24292e;"></i></a></div></div><div class="card-widget card-announcement"><div class="item-headline"><i class="fas fa-bullhorn fa-shake"></i><span>公告</span></div><div class="announcement_content">FlyingZC's Blog</div></div><div class="sticky_layout"><div class="card-widget" id="card-toc"><div class="item-headline"><i class="fas fa-stream"></i><span>目录</span><span class="toc-percentage"></span></div><div class="toc-content"><ol class="toc"><li class="toc-item toc-level-1"><a class="toc-link" href="#Omid-Timestamp-Oracle-%E7%BB%84%E4%BB%B6%E5%AE%9E%E7%8E%B0%E5%8E%9F%E7%90%86"><span class="toc-number">1.</span> <span class="toc-text">Omid Timestamp Oracle 组件实现原理</span></a><ol class="toc-child"><li class="toc-item toc-level-2"><a class="toc-link" href="#%E4%BD%9C%E7%94%A8"><span class="toc-number">1.1.</span> <span class="toc-text">作用</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E5%8A%9F%E8%83%BD"><span class="toc-number">1.2.</span> <span class="toc-text">功能</span></a></li><li class="toc-item toc-level-2"><a class="toc-link" href="#%E7%B1%BB"><span class="toc-number">1.3.</span> <span class="toc-text">类</span></a><ol class="toc-child"><li class="toc-item toc-level-3"><a class="toc-link" href="#TimestampStorage"><span class="toc-number">1.3.1.</span> <span class="toc-text">TimestampStorage</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#ZKTimestampStorage"><span class="toc-number">1.3.1.1.</span> <span class="toc-text">ZKTimestampStorage</span></a></li></ol></li><li class="toc-item toc-level-3"><a class="toc-link" href="#TimestampOracle"><span class="toc-number">1.3.2.</span> <span class="toc-text">TimestampOracle</span></a><ol class="toc-child"><li class="toc-item toc-level-4"><a class="toc-link" href="#%E5%AE%9E%E7%8E%B0%E7%B1%BB"><span class="toc-number">1.3.2.1.</span> <span class="toc-text">实现类</span></a></li><li class="toc-item toc-level-4"><a class="toc-link" href="#TimestampOracleImpl"><span class="toc-number">1.3.2.2.</span> <span class="toc-text">TimestampOracleImpl</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#initialize"><span class="toc-number">1.3.2.2.1.</span> <span class="toc-text">initialize()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#next"><span class="toc-number">1.3.2.2.2.</span> <span class="toc-text">next()</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#AllocateTimestampBatchTask"><span class="toc-number">1.3.2.2.3.</span> <span class="toc-text">AllocateTimestampBatchTask</span></a></li></ol></li><li class="toc-item toc-level-4"><a class="toc-link" href="#WorldClockOracleImpl"><span class="toc-number">1.3.2.3.</span> <span class="toc-text">WorldClockOracleImpl</span></a><ol class="toc-child"><li class="toc-item toc-level-5"><a class="toc-link" href="#AllocateTimestampBatchTask-run"><span class="toc-number">1.3.2.3.1.</span> <span class="toc-text">AllocateTimestampBatchTask#run</span></a></li><li class="toc-item toc-level-5"><a class="toc-link" href="#next-1"><span class="toc-number">1.3.2.3.2.</span> <span class="toc-text">next()</span></a></li></ol></li></ol></li></ol></li></ol></li></ol></div></div><div class="card-widget card-recent-post"><div class="item-headline"><i class="fas fa-history"></i><span>最新文章</span></div><div class="aside-list"><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite03-transaction-begin.html" title="Apache Ignite 开启事务执行流程">Apache Ignite 开启事务执行流程</a><time datetime="2025-10-10T16:00:00.000Z" title="发表于 2025-10-11 00:00:00">2025-10-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite02-transaction.html" title="Apache Ignite 分布式事务原理">Apache Ignite 分布式事务原理</a><time datetime="2025-09-17T16:00:00.000Z" title="发表于 2025-09-18 00:00:00">2025-09-18</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/ignite/ignite01-build.html" title="Apache Ignite IDEA 环境搭建">Apache Ignite IDEA 环境搭建</a><time datetime="2025-09-10T16:00:00.000Z" title="发表于 2025-09-11 00:00:00">2025-09-11</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/druid/druid01-resultset-leak.html" title="ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析">ShardingSphere JDBC 使用 Druid 连接池 ResultSet 内存泄露分析</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div><div class="aside-list-item no-cover"><div class="content"><a class="title" href="/articles/jmeter/jmeter01-shardingsphere.html" title="Jmeter 压测 ShardingSphere">Jmeter 压测 ShardingSphere</a><time datetime="2025-06-30T16:00:00.000Z" title="发表于 2025-07-01 00:00:00">2025-07-01</time></div></div></div></div></div></div></main><footer id="footer"><div id="footer-wrap"><div class="copyright">&copy;2020 - 2025 By flyingzc</div></div></footer></div><div id="rightside"><div id="rightside-config-hide"><button id="readmode" type="button" title="阅读模式"><i class="fas fa-book-open"></i></button><button id="darkmode" type="button" title="日间和夜间模式切换"><i class="fas fa-adjust"></i></button><button id="hide-aside-btn" type="button" title="单栏和双栏切换"><i class="fas fa-arrows-alt-h"></i></button></div><div id="rightside-config-show"><button id="rightside-config" type="button" title="设置"><i class="fas fa-cog fa-spin"></i></button><button class="close" id="mobile-toc-button" type="button" title="目录"><i class="fas fa-list-ul"></i></button><button id="go-up" type="button" title="回到顶部"><span class="scroll-percent"></span><i class="fas fa-arrow-up"></i></button></div></div><div><script src="/js/utils.js"></script><script src="/js/main.js"></script><div class="js-pjax"></div><script async data-pjax src="//busuanzi.ibruce.info/busuanzi/2.3/busuanzi.pure.mini.js"></script></div></body></html>